package app

import (
	"github.com/go-redis/redis/v8"
	"strconv"
)

var RedisClusterConn *redis.ClusterClient

var (
	DefaultRedisConn = "cluster"
	RedisConn        = make(map[string]*redis.ClusterClient)
)

// 获取链接 默认链接的是集群 cluster
func RedisCluster(options ...string) *redis.ClusterClient {

	CurrentDbConn := "cluster"
	if len(options) == 1 && options[0] != "" {
		CurrentDbConn = options[0]
	}

	key := CurrentDbConn

	if _, ok := RedisConn[key]; ok {
		return RedisConn[key]
	}

	RedisClusterConn = InitRedisCluster()
	return RedisClusterConn
}

// 初始化
func InitRedisCluster() *redis.ClusterClient {

	// 获取配置
	redisConfig, errRedisConfig := Config.GetRedisClusterConfig()
	if errRedisConfig != nil {
		panic(errRedisConfig.Error())
	}

	clusterArr := make([]string, 0)
	for _, item := range redisConfig {
		clusterArr = append(clusterArr, item.RedisHost+":"+strconv.FormatInt(item.RedisPort, 10))
	}

	// 连接
	return redis.NewClusterClient(&redis.ClusterOptions{
		Addrs:    clusterArr,
		Username: "",
		Password: "1234",
	})
}
